package cc.orange.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import demo.smart.access.xutlis.util.ZXToastUtil;

/**
 * Created by CM on 2021/7/26.
 */

public class ImgDownLoadUtils {
    public static String getDownloadPath(Context context) {

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //android 11
//            return ContentsImg.SDCardConstants.getDir(context) + File.separator;
//        }else {
//            String path;
////            File sdcardDir = context.getExternalFilesDir(null);
////            if (sdcardDir == null) {
//                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mxxq/";
////            }else {
////                path = sdcardDir + "/mxxq/";
////            }
////            return Environment.getExternalStorageState() + "/mxxq/";
//            return path;
//        }

        String dir;
        if (Build.VERSION.SDK_INT > 30) {
            dir = context.getExternalFilesDir("") + File.separator + "mizhiji" + File.separator;
        } else {
            dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mizhiji/";
        }
//        File file = new File(dir);
//        if (!file.exists()) {
//            //noinspection ResultOfMethodCallIgnored
//            file.mkdirs();
//        }
        return dir;
    }

    //星球专用
    public static void getImagFile2(Context context,String url,String name,
                                   SuccessListener success){
        Log.v("=====file",url);
        Glide.with(context).downloadOnly()
                .load(url)
                .addListener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        ZXToastUtil.showToast("下载失败");
                        if(null != success){
                            success.onFail("失败");
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
//                        ZXToastUtil.showToast("下载成功");
                        saveToAlbum2(context,resource,name);
                        if(null != success){
                            success.onSuccessDown("成功");
                        }
                        return false;
                    }
                }).preload();
    }

    //    * 保存到相册中2  星球专用
//     * @param context 上下文
//     * @param srcPath 网络图保存到本地的缓存文件路径
//     */
    private static void saveToAlbum2(Context context, File fils,String name) {
//        Bitmap waterBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_load_img);
        Bitmap bitmap =BitmapFactory.decodeFile(fils.getAbsolutePath());
        // 计算缩放比例.

        String dcimPath = getDownloadPath(context);
        try {
            File file1 = new File(dcimPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
//        Bitmap textBitmap4 = ImageUtil.createWaterMaskRightBottom("@"+name,context, bitmap, waterBitmap, 0, 0);
//        Bitmap textBitmap4 = ImageUtil.drawTextToRightBottom(context, watermarkBitmap2, "@"+name, textsize, Color.WHITE, padingright, padingbottom);
        boolean compress = false;
        File file = new File(dcimPath, "content_" + System.currentTimeMillis() + ".png");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            compress = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (compress) {
            //发送广播通知
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
            ZXToastUtil.showToast("图片保存到相册成功");
            if(Build.VERSION.SDK_INT >= 30){
                saveImageToGallery2(context,bitmap);
            }
        } else {
            ZXToastUtil.showToast("图片保存到相册失败");
        }
    }

    public static void saveToAlbumBitmap(Context context, Bitmap bitmap,String name,
                                         SuccessListener success) {

        String dcimPath = getDownloadPath(context);
        try {
            File file1 = new File(dcimPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        boolean compress = false;
        File file = new File(dcimPath, "content_" + System.currentTimeMillis() + ".png");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            compress = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (compress) {
            //发送广播通知
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
            ZXToastUtil.showToast("图片保存到相册成功");
            if(Build.VERSION.SDK_INT >= 30){
                saveImageToGallery2(context,bitmap);
            }
            if(null != success){
                success.onSuccessDown("");
            }
        } else {
            if(null != success){
                success.onFail("");
            }
            ZXToastUtil.showToast("图片保存到相册失败");
        }
    }

    /**
     * android 11及以上保存图片到相册
     * @param context
     * @param image
     */
    @RequiresApi(api = 30)
    public static void saveImageToGallery2(Context context, Bitmap image){
        Long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "mizhiji_%s.png";//图片名称，以"winetalk"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);

        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "mi_zhiji"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"dh"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();
        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
//            try (OutputStream out = resolver.openOutputStream(uri)) {
//                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
//                    throw new IOException("Failed to compress");
//                }
//            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
        }catch (Exception e){
            Log.v("---","Exception:"+e.toString());
        }
    }


    public interface SuccessListener{
        void onSuccessDown(String se);
        void onFail(String se);
    }
}
